import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Department } from '../models/department.entity';

@Injectable()
export class DepartmentService {
  constructor(
    @InjectRepository(Department)
    private departmentRepository: Repository<Department>,
  ) {}

  findAll(): Promise<Department[]> {
    return this.departmentRepository.find();
  }

  findOne(id: number): Promise<Department | null> {
    return this.departmentRepository.findOneBy({ id });
  }

  create(deptData: Partial<Department>): Promise<Department> {
    const department = this.departmentRepository.create(deptData);
    return this.departmentRepository.save(department);
  }

  async update(
    id: number,
    deptData: Partial<Department>,
  ): Promise<Department | null> {
    const department = await this.findOne(id);
    if (!department) {
      return null;
    }
    this.departmentRepository.merge(department, deptData);
    return this.departmentRepository.save(department);
  }

  async remove(id: number): Promise<Department | null> {
    const department = await this.findOne(id);
    if (!department) {
      return null;
    }
    return this.departmentRepository.remove(department);
  }
}
